package com.taotao.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.taotao.common.pojo.EUDataGridResult;
import com.taotao.common.pojo.TaotaoResult;
import com.taotao.mapper.TbItemDescMapper;
import com.taotao.mapper.TbItemMapper;
import com.taotao.mapper.TbItemParamItemMapper;
import com.taotao.pojo.TbItem;
import com.taotao.pojo.TbItemDesc;
import com.taotao.pojo.TbItemExample;
import com.taotao.pojo.TbItemParamItem;
import com.taotao.utils.IDUtils;

@Service
public class ItemServiceImpl implements ItemService {
	@Autowired
	TbItemMapper itemMapper;
	
	@Autowired
	TbItemDescMapper itemDescMapper;
	
	@Autowired
	TbItemParamItemMapper itemParamItemMapper;
	

	@Override
	public TbItem getItemById(long itemId) {
		TbItem item = itemMapper.selectByPrimaryKey(itemId);
		if (item != null) {
			return item;
		}
		return null;
	}


	@Override
	public EUDataGridResult getItemList(int page, int rows) {
		TbItemExample example = new TbItemExample();
		PageHelper.startPage(page, rows);
		List<TbItem> list = itemMapper.selectByExample(example);
		EUDataGridResult result = new EUDataGridResult();
		result.setRows(list);
		PageInfo<TbItem> pageInfo = new PageInfo<TbItem>(list);
		result.setTotal(pageInfo.getTotal());
		
		return result;
	}


	@Override
	public TaotaoResult createItem(TbItem item, String desc, String paramData) throws Exception {
		//商品信息补全
		//生成商品ID
		Long itemId = IDUtils.genItemId();
		item.setId(itemId);
		item.setStatus((byte) 1);
		item.setCreated(new Date());
		item.setUpdated(new Date());
		
		itemMapper.insert(item);
		TaotaoResult resultDesc = insertDesc(itemId, desc);
		
		if(resultDesc.getStatus() != 200) {
			throw new Exception("描述添加失败");
		}
		
		TaotaoResult resultParam = insertItemParams(itemId, paramData);
		if(resultParam.getStatus() != 200) {
			throw new Exception("规格添加失败");
		}
		return TaotaoResult.ok();
	}
	
	private TaotaoResult insertDesc(Long itemId, String desc) {
		TbItemDesc itemDesc = new TbItemDesc();
		itemDesc.setItemId(itemId);
		itemDesc.setItemDesc(desc);
		itemDesc.setCreated(new Date());
		itemDesc.setUpdated(new Date());
		itemDescMapper.insert(itemDesc);
		return TaotaoResult.ok();
	}
	
	private TaotaoResult insertItemParams(Long itemId, String paramData) {
		TbItemParamItem paramItem = new TbItemParamItem();
		paramItem.setItemId(itemId);
		paramItem.setParamData(paramData);
		paramItem.setCreated(new Date());
		paramItem.setUpdated(new Date());
		itemParamItemMapper.insert(paramItem);
		return TaotaoResult.ok();
	}

}
